import 'package:flutter/material.dart';
import 'package:flutter_parsed_text/flutter_parsed_text.dart';
import 'package:get/get.dart';
import 'package:live_music/models/topic_detail_model.dart';
import 'package:live_music/pages/topic/topic_detail.dart';
import 'package:live_music/services/topicService.dart';

class FormattedText extends StatelessWidget {
  final String text;
  final TextStyle style;
  final TextAlign textAlign;
  final TextDirection textDirection;
  final TextOverflow overflow;
  final int maxLines;

  final parse = <MatchText>[
    MatchText(
      pattern: r"(@[\u4e00-\u9fa5_a-zA-Z0-9]+)",
      renderWidget: ({pattern, text}) => Text(
        text,
        style: TextStyle(
          color: Colors.blueAccent,
        ),
      ),
      onTap: (String username) {
        print(username.substring(1));
      },
    ),
    MatchText(
      pattern: r"(#[\u4e00-\u9fa5_a-zA-Z0-9]+)",
      renderWidget: ({pattern, text}) => Text(
        text,
        style: TextStyle(
          color: Colors.blueAccent[400],
        ),
      ),
      onTap: (String name) async {
        Map<String, dynamic> topicData =
            await TopicService.getTopicDetail({"name": name.substring(1)});
        TopicDetailModel topicItem =
            TopicDetailModel.fromJson(topicData['body']);
        Get.to(TopicDetailPage(topicItem: topicItem));
      },
    ),
  ];

  FormattedText(
    this.text, {
    Key key,
    this.style,
    this.textAlign,
    this.textDirection,
    this.overflow,
    this.maxLines,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final defaultTextStyle = DefaultTextStyle.of(context);

    return ParsedText(
      text: text,
      style: style ?? defaultTextStyle.style,
      alignment: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start,
      textDirection: textDirection ?? Directionality.of(context),
      overflow: overflow ?? TextOverflow.clip,
      maxLines: maxLines ?? defaultTextStyle.maxLines,
      parse: parse,
      regexOptions: RegexOptions(caseSensitive: false),
    );
  }
}
